const chokidar = require("chokidar");
const WatchEvents = ["ready", "add", "unlink", "change", "addDir", "unlinkDir"];
const DebounceTimer = 200;
// 弄个防抖
function debounce(fn, wait) {
    let timeout;
    return function () {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
            fn.apply(this, arguments);
            timeout = null;
        }, wait);
    };
}

function startWatch(paths, cb) {
    let pathArr = Array.isArray(paths) ? paths : [paths];
    // 监视当前目录下的所有文件和子目录
    const toCallBack = debounce(() => {
        if (typeof cb === "function") {
            cb();
        }
    }, DebounceTimer);
    const watcher = chokidar.watch(pathArr, { ignoreInitial: true });
    // 只监听那几个事件吧
    WatchEvents.forEach((e) => {
        // 弄个防抖
        watcher.on(e, toCallBack);
    });
}

module.exports = {
    startWatch,
};
